package services

import (
	"errors"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	"hft/Http/Models/request"
	utils "hft/Http/Utils"
	"hft/global"
	"strconv"
	"strings"
)

type LouPanPhone struct{}

func (*LouPanPhone) Create(data *admin.LouPanPhone) (err error) {

	var region *admin.Region

	global.OC_DB.First(&region)

	var belongArr []*admin.Region

	var regionStrArr = strings.Split(region.Link, ",")
	regionStrArr = regionStrArr[2 : len(regionStrArr)-1]
	var regionIds []int

	for _, v := range regionStrArr {
		id, _ := strconv.Atoi(v)
		regionIds = append(regionIds, id)
	}

	regionIds = append(regionIds, int(region.ID))

	global.OC_DB.Find(&belongArr, regionIds)

	var belongStrArr []string

	for _, v := range belongArr {
		belongStrArr = append(belongStrArr, v.Name)
	}

	data.Belong = strings.Join(belongStrArr, "-")

	res := global.OC_DB.Where("phone = ?", data.Phone).FirstOrCreate(&data)

	if res.Error != nil {
		return errors.New("未知错误500")
	}

	if res.RowsAffected == 0 {
		return errors.New("该分机号已被使用")
	}

	return nil
}

func (*LouPanPhone) Edit(data *admin.LouPanPhone) (err error) {

	var region *admin.Region

	global.OC_DB.First(&region)

	var belongArr []*admin.Region

	var regionStrArr = strings.Split(region.Link, ",")
	regionStrArr = regionStrArr[2 : len(regionStrArr)-1]
	var regionIds []int

	for _, v := range regionStrArr {
		id, _ := strconv.Atoi(v)
		regionIds = append(regionIds, id)
	}

	regionIds = append(regionIds, int(region.ID))

	global.OC_DB.Find(&belongArr, regionIds)

	var belongStrArr []string

	for _, v := range belongArr {
		belongStrArr = append(belongStrArr, v.Name)
	}

	data.Belong = strings.Join(belongStrArr, "-")

	err = global.OC_DB.Where("phone = ?", data.Phone).Updates(&data).Error

	if err != nil {
		return errors.New("该分机已被占用")
	}

	return nil
}

func (*LouPanPhone) List(paginate *request.LouPanPhonePage) (data *utils.Page, err error) {

	var phones []*admin.LouPanPhone

	global.OC_DB.Scopes(dao.LouPanPhoneDao.List(*paginate, global.OC_DB)).Find(&phones).Scopes(dao.GetCount(global.OC_DB)).Count(&paginate.Total)

	paginate.Data = phones

	return &paginate.Page, nil
}

func (*LouPanPhone) Delete(ids []int) (err error) {

	var phones []*admin.LouPanPhone

	global.OC_DB.Find(&phones)

	global.OC_DB.Unscoped().Delete(&phones)

	return nil

}

var LouPanPhoneService = new(LouPanPhone)
